package org.omich.loaves;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;
import java.io.StreamCorruptedException;

import android.os.Handler;
import android.os.Message;

public class BluetoothBrainServer /*extends BluetoothMessageGetter*/ {
	private IMessageHandler mMessageHandler = new IMessageHandler() {
		public void handle(Object object) {
			if (object instanceof GetStatusMessage)
				mTransport.SendMessage(mBrain.getStatus());
			if (object instanceof TryEatingMessage) {
				TryEatingMessage message = (TryEatingMessage)object;
				mBrain.tryToEatLoaf(message.getPlayerName(), message.getLoafNumber());
			}
		}
	};
	private IBrain mBrain;
	
	 private final Handler mHandler = new Handler() {
	        @Override
	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	            case LoavesActivity.MESSAGE_READ:
	                byte[] readBuf = (byte[]) msg.obj;
	                Object ob;
	                try {
	                	ob = new ObjectInputStream(new ByteArrayInputStream(readBuf)).readObject();
	                	mMessageHandler.handle(ob);
					} catch (OptionalDataException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (StreamCorruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	        }
	    };

	    private INetworkTransport mTransport; 
	    
	public BluetoothBrainServer(IBrain brain, INetworkTransport transport) {
		mTransport = transport;
		mBrain = brain;
		transport.SetMessageProcessorHandler(mHandler);
	}

	/*public String getPlayerName() {
		return mBtService.getName();
	}*/

	/*public boolean isConnected() {
		return mBtService.getState() == BluetoothService.STATE_CONNECTED;
	}*/
}
